package com.itxb.glmall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itxb.common.utils.PageUtils;
import com.itxb.common.utils.Query;

import com.itxb.glmall.product.dao.CategoryDao;
import com.itxb.glmall.product.entity.CategoryEntity;
import com.itxb.glmall.product.service.CategoryService;


/**
 * @author Gordon
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 以树形结构返回数据
     *
     * @return 以树形结构返回数据
     */
    @Override
    public List<CategoryEntity> listTree() {
        //全部数据
        List<CategoryEntity> entities = getBaseMapper().selectList(null);

        List<CategoryEntity> level1Menu = entities.stream().filter(categoryEntity -> categoryEntity.getCatLevel() == 1)
                .map(menu -> {
                    List<CategoryEntity> children = getChildren(menu, entities);
                    menu.setChildren(children);
                    return menu;
                })
                .collect(Collectors.toList());
        return level1Menu;
    }

    /**
     * 递归方式获取子集数据
     *
     * @param root 当前级别
     * @param all  所有数据
     * @return 获取当前级别数据所有子集数据
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> categoryEntity.getParentCid() == (root.getCatId()))
                .map(menu -> {
                    menu.setChildren(getChildren(menu, all));
                    return menu;
                })
                .collect(Collectors.toList());
        return children;
    }

}